<?php
namespace app\api\controller;

use think\facade\Db;

class ApiComData
{

    /**
     * @param array $param
     * @return array
     */
    public static function xmlSend($param = [])
    {
        $card_type_array = [
            1 => [
                "556305" => ['code' => 'W-990' , 'id' => 'CLSWX'],
                "556766" => ['code' => 'P-616' , 'id' => 'CKH7L'],
                "558068" => ['code' => 'P-616' , 'id' => 'DE0R4'],
                "531847" => ['code' => 'P-616' , 'id' => 'DE0R3'],
                "556735" => ['code' => 'P-616' , 'id' => 'CKGNT'],
                "527811" => ['code' => 'W-990' , 'id' => 'DF4RP']
            ],
            2=>[
                "556766" => ['code' => 'M-75J' , 'id' => 'DFG8Y']
            ],
        ];
        $user_pwd_array  = [
            1 => [
                "username" => 'WSPPTCO',
//                "password" => 'ge$$RAdDZb3p'
                "password" => '9YJRsbjz3JC4'
            ],
            2=>[
                "username" => '165939289935389667',
                "password" => '3$Kq!KJh2B#p'
            ],
        ];
        $bank_type      = $param['bank_type'] ?? 1;
        $card_type      = $param['card_type'];
        $accountCode    = $card_type_array[$bank_type][$card_type]['code'];
        $customerId     = $card_type_array[$bank_type][$card_type]['id'];
        $username       = $user_pwd_array[$bank_type]['username'];
        $password       = $user_pwd_array[$bank_type]['password'];
        $soap_header=  '<soapenv:Header>
                            <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                                <wsse:UsernameToken>
                                    <wsse:Username>' . $username . '</wsse:Username>
                                    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $password . '</wsse:Password>
                                </wsse:UsernameToken>
                            </wsse:Security>
                        </soapenv:Header>';
        $soap_body  = '';
        $soap_action= '';

        $action_type= $param['action_type'];
        $user_id    = $param['user_id'] ?? 1;
        $send_param = $param['post_param'];
        $card_num   = $send_param['card_num'] ?? '';
        switch ($action_type){
            case "addCard":
                $soap_action    = "addCardV02";
                $cardFirstName  = $send_param['first_name'];
                $cardLastName   = $send_param['last_name'];
                $employeeNumber = $send_param['memo'];
                $exp_time       = $send_param['exp_time'];
                $soap_body .="<main:AddCardRequestV02>
                                <cardDetails>
                                    <accountCode>{$accountCode}</accountCode>
                                    <customerId>{$customerId}</customerId>
                                    <cardStatus>A</cardStatus>
                                    <profileFlag>N</profileFlag>
                                    <cardFirstName>{$cardFirstName}</cardFirstName>
                                    <cardLastName>{$cardLastName}</cardLastName>
                                    <employeeNumber>{$employeeNumber}</employeeNumber>";
                if($card_type == '556766' || $card_type == '558068' || $card_type == '531847'){
                    $soap_body .="<cardExpiration>{$exp_time}</cardExpiration>";
                }
                $soap_body .="</cardDetails>
                            </main:AddCardRequestV02>";
                break;
            case "addCard2":
                $soap_action    = "addCardV03";
                $cardFirstName  = $send_param['first_name'];
                $cardLastName   = $send_param['last_name'];
                $employeeNumber = $send_param['memo'];
                $exp_time       = $send_param['exp_time'];
                $card_balance   = $send_param['card_balance'];
                $soap_body ="<main:AddCardRequestV03>
                                <cardDetails>
                                    <accountCode>{$accountCode}</accountCode>
                                    <customerId>{$customerId}</customerId>
                                    <cardStatus>A</cardStatus>
                                    <profileFlag>N</profileFlag>
                                    <cardFirstName>{$cardFirstName}</cardFirstName>
                                    <cardLastName>{$cardLastName}</cardLastName>
                                    <employeeNumber>{$employeeNumber}</employeeNumber>";
                if($card_type == '556766' || $card_type == '558068' || $card_type == '531847'){
                    $soap_body .="<cardExpiration>{$exp_time}</cardExpiration>";
                }
                $soap_body   .="</cardDetails>
                                <profileLimits>
                                    <openCloseFlag>O</openCloseFlag>
                                    <productAvailableFlag>Y</productAvailableFlag>
                                    <transactionDollarLimit>{$card_balance}</transactionDollarLimit>
                                    <dailyDollarLimit>{$card_balance}</dailyDollarLimit>
                                    <dailyTransactionLimit>999</dailyTransactionLimit>
                                    <cycleDollarLimit>{$card_balance}</cycleDollarLimit>
                                    <cycleTransactionLimit>999</cycleTransactionLimit>
                                    <cycleType>T</cycleType>
                                    <cycleDay>T</cycleDay>
                                </profileLimits>
                            </main:AddCardRequestV03>";
                break;
            case "updateCardLimits":
                $soap_action    = "updateCardProfileLimits";
                //1
                $soap_body      = self::cardProfileXml($accountCode,$customerId,$card_num,$send_param['card_balance']);
                break;
            case "add_card_balance":
                $soap_action    = "updateCardProfileLimits";
                //2
                $soap_body      = self::cardProfileXml($accountCode,$customerId,$card_num,$send_param['card_balance']);
                break;
            case "deduct_card_balance":
                $soap_action    = "updateCardProfileLimits";
                //3
                $soap_body      = self::cardProfileXml($accountCode,$customerId,$card_num,$send_param['card_balance']);
                break;
            case "searchExpDate":
                $soap_action    = "inquireCardV02";
                $soap_body      =  "<main:CardInquiryRequestV02>
                                    <accountCode>{$accountCode}</accountCode>
                                    <customerId>{$customerId}</customerId>
                                    <cardIdentifierType>C</cardIdentifierType>
                                    <cardIdentifier>{$card_num}</cardIdentifier>
                                </main:CardInquiryRequestV02>";
                break;
            case "searchExpDate2":
                //定时任务 不记录api
                $soap_action    = "inquireCardV02";
                $soap_body      =  "<main:CardInquiryRequestV02>
                                    <accountCode>{$accountCode}</accountCode>
                                    <customerId>{$customerId}</customerId>
                                    <cardIdentifierType>C</cardIdentifierType>
                                    <cardIdentifier>{$card_num}</cardIdentifier>
                                </main:CardInquiryRequestV02>";
                break;
            case "searchCard2Token":
                $card_token     = $send_param['card_token'];
                $soap_action    = "inquireCardV02";
                $soap_body      =  "<main:CardInquiryRequestV02>
                                    <accountCode>{$accountCode}</accountCode>
                                    <customerId>{$customerId}</customerId>
                                    <cardIdentifierType>T</cardIdentifierType>
                                    <cardIdentifier>{$card_token}</cardIdentifier>
                                    </main:CardInquiryRequestV02>";
                break;
            case "searchCvv":
                $soap_action    = "inquireCardSecurityCode";
                $exp_date       = $send_param['exp_date'];
                $soap_body =  " <main:CardSecurityCodeInquiryRequest>
                                     <accountCode>{$accountCode}</accountCode>
                                     <customerId>{$customerId}</customerId>
                                     <empNumCardNumFlag>C</empNumCardNumFlag>
                                     <empNumCardNumValue>{$card_num}</empNumCardNumValue>
                                     <cardExpirationDate>{$exp_date}</cardExpirationDate>
                                </main:CardSecurityCodeInquiryRequest>";
                break;
            case "card_active":
                $soap_action    = "updateCardV02";
                $soap_body      = self::updateCardStatus($accountCode,$customerId,$card_num,'A');
                break;
            case "card_active_new":
                $soap_action    = "updateCardV02";
                $soap_body      = self::updateCardStatusNew($accountCode,$customerId,$card_num,'A');
                break;
            case "card_suspended":
                $soap_action    = "updateCardV02";
                //1
                $soap_body      = self::updateCardStatus($accountCode,$customerId,$card_num,'B');
                break;
            case "card_del_unReal":
                $soap_action    = "updateCardV02";
                //2
                $soap_body      = self::updateCardStatus($accountCode,$customerId,$card_num,'B');
                break;
            case "card_del":
                $soap_action    = "updateCardV02";
                $soap_body      = self::updateCardStatus($accountCode,$customerId,$card_num,'C');
                break;
            case "updateCard":
                $soap_action    = "updateCardV02";
                $address        = $send_param['address'];
                $city           = $send_param['city'];
                $state          = $send_param['state'];
                $zip            = $send_param['zip'];
                $soap_body =  "<main:UpdateCardRequestV02>
                                    <cardIdentifierType>C</cardIdentifierType>
                                    <cardIdentifier>{$card_num}</cardIdentifier>
                                    <cardDetails>
                                        <accountCode>{$accountCode}</accountCode>
                                        <customerId>{$customerId}</customerId>
                                        <profileFlag>N</profileFlag>
                                    </cardDetails>
                                    <mailingDetails>            
                                        <mailAddress1>{$address}</mailAddress1>
                                        <mailCity>{$city}</mailCity>
                                        <mailState>{$state}</mailState>
                                        <mailZip>{$zip}</mailZip>
                                    </mailingDetails>
                                </main:UpdateCardRequestV02>";
                break;
            case "search_funds":
                $soap_action    = "paymentHistory";
                $soap_body =  "<main:PaymentHistoryRequest>
                                 <accountCode>{$accountCode}</accountCode>
                              </main:PaymentHistoryRequest>";
                break;
            case "search_account":
                $soap_action    = "availableCreditInquiry";
                $soap_body =  "<main:AvailableCreditInquiryRequest>
                                 <accountCodes>
                                    <accountCode>{$accountCode}</accountCode>
                                 </accountCodes>
                                 <activeAccountsOnly>true</activeAccountsOnly>
                              </main:AvailableCreditInquiryRequest>";
                break;
            case "search_trans":
                $soap_action    = "realTimeTransactionHistory";
                $startDate      = $send_param['startDate'];
                $soap_body =  "<main:RtTransactionRequest>
                                    <criteria>
                                        <accountCode>{$accountCode}</accountCode>
                                        <customerIds>
                                            <!--Zero or more repetitions:-->
                                            <customerId>{$customerId}</customerId>
                                        </customerIds>
                                        <transactionStatuses>
                                           <!--Zero or more repetitions:-->
                                            <transactionStatus>All</transactionStatus>
                                        </transactionStatuses>
                                        <sortByDateType>Transaction</sortByDateType>
                                        <selectionDateType>Transaction</selectionDateType>
                                        <startDate>{$startDate}</startDate>
                                 </criteria>
                                 <pageNbr>1</pageNbr>
                              </main:RtTransactionRequest>";
                break;
            case "search_trans_only":
                $soap_action    = "realTimeTransactionHistory";
                $startDate      = $send_param['startDate'];
                $soap_body      =  "<main:RtTransactionRequest>
                                    <criteria>
                                        <accountCode>{$accountCode}</accountCode>
                                        <customerIds>
                                            <!--Zero or more repetitions:-->
                                            <customerId>{$customerId}</customerId>
                                        </customerIds>
                                        <cardNumber>{$card_num}</cardNumber>
                                        <transactionStatuses>
                                           <!--Zero or more repetitions:-->
                                            <transactionStatus>All</transactionStatus>
                                        </transactionStatuses>
                                        <sortByDateType>Transaction</sortByDateType>
                                        <selectionDateType>Transaction</selectionDateType>
                                        <startDate>{$startDate}</startDate>
                                 </criteria>
                                 <pageNbr>1</pageNbr>
                              </main:RtTransactionRequest>";
                break;
            case "search_trans_all":
                $soap_action    = "realTimeTransactionHistory";
                $startDate      = $send_param['startDate'];
                $endDate        = $send_param['endDate'];
                $soap_body      =  "<main:RtTransactionRequest>
                                    <criteria>
                                        <accountCode>{$accountCode}</accountCode>
                                        <customerIds>
                                            <!--Zero or more repetitions:-->
                                            <customerId>{$customerId}</customerId>
                                        </customerIds>
                                        <transactionStatuses>
                                           <!--Zero or more repetitions:-->
                                            <transactionStatus>All</transactionStatus>
                                        </transactionStatuses>
                                        <sortByDateType>Transaction</sortByDateType>
                                        <selectionDateType>Transaction</selectionDateType>
                                        <startDate>{$startDate}</startDate>
                                        <endDate>{$endDate}</endDate>
                                 </criteria>
                                 <pageNbr>1</pageNbr>
                              </main:RtTransactionRequest>";
                break;
            case "search_trans_test":
                $soap_action    = "realTimeTransactionHistory";
                $startDate      = $send_param['startDate'];
                $endDate        = $send_param['endDate'];
                $soap_body      =  "<main:RtTransactionRequest>
                                    <criteria>
                                        <accountCode>{$accountCode}</accountCode>
                                        <customerIds>
                                            <!--Zero or more repetitions:-->
                                            <customerId>{$customerId}</customerId>
                                        </customerIds>
                                        <cardNumber>{$card_num}</cardNumber>
                                        <transactionStatuses>
                                           <!--Zero or more repetitions:-->
                                            <transactionStatus>All</transactionStatus>
                                        </transactionStatuses>
                                        <sortByDateType>Transaction</sortByDateType>
                                        <selectionDateType>Transaction</selectionDateType>
                                        <startDate>{$startDate}</startDate>
                                        <endDate>{$endDate}</endDate>
                                 </criteria>
                                 <pageNbr>1</pageNbr>
                              </main:RtTransactionRequest>";
                break;
            case "up_card_balance":
                $pageNumber      = $send_param['pageNumber'];
                $soap_action   = "cardListingV02";
                $soap_body       =  "<main:CardListingRequestV02>
                                 <acctCustidList>
                                    <acctCustidElement>
                                       <accountCode>{$accountCode}</accountCode>
                                       <custIdList>
                                          <customerId>{$customerId}</customerId>
                                       </custIdList>
                                    </acctCustidElement>
                                 </acctCustidList>
                                 <maxRows>100</maxRows>
                                 <pageNumber>{$pageNumber}</pageNumber>
                              </main:CardListingRequestV02>";
                break;
            default:
                break;
        }
        $xml_post_string = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:main="http://fleetCredit02.comdata.com/maintenance/">';
        $xml_post_string.=  $soap_header;
        $xml_post_string.=  '<soapenv:Body>';
        $xml_post_string.=  $soap_body;
        $xml_post_string.=  '</soapenv:Body>';
        $xml_post_string.=  '</soapenv:Envelope>';

        $url        = "https://api.iconnectdata.com/FleetCreditWS/services/FleetCreditWS0200/wsdl/FleetCreditWS0200.wsdl";
        $header     = [
            'trace' => TRUE,
            'exceptions' => TRUE,
            'cache_wsdl' => WSDL_CACHE_BOTH,
            'stream_context' => stream_context_create(array(
                'http' => array(
                    'header' => 'SOAPAction: "http://fleetCredit02.comdata.com/FleetCreditWS0200/' . $soap_action . '"'
                ),
            ))
        ];
        $soapClient = new \SoapClient($url, $header);
        $response = $soapClient->__doRequest($xml_post_string, 'https://api.iconnectdata.com/FleetCreditWS/services/FleetCreditWS0200', $soap_action, SOAP_1_2);

        $xml_read = new \DOMDocument();
        //有可能api请求频繁,导致获取到空值
        if(empty($response)){
            $return_result = ['blog' => false,'list' =>['error_string' => 'get data error']];
            Db::name('cd_api_log')->save([
                'user_id'           => $user_id,
                'name'              => $action_type,
                'card_num'          => $card_num,
                'ip'                => get_client_ip(),
                'header'            => $soap_action,
                'method'            => 'POST',
                'request'           => $soap_body,
                'response'          => $response,
                'response_json'     => json_encode($return_result),
                'ctime'             => getUtcTime()
            ]);
            return $return_result;
        }
        $xml_read->loadXML($response);

        /** 先判断错误 **/
        $error_code     = '';
        $error_string   = '';
        $list           = [];
        foreach ($xml_read->lastChild->lastChild->lastChild->childNodes as $dom){
            if($dom->tagName == "faultcode"){
                $error_code     = $dom->textContent ?? '';
            }
            if($dom->tagName == "faultstring"){
                $error_string   = $dom->textContent ?? '';
            }
            if($action_type == "searchExpDate" || $action_type == "searchCard2Token" || $action_type == "searchExpDate2"){
                //获取卡号
                if($dom->tagName == "cardNumber")
                    $list['cardNumber'] = $dom->textContent ?? '';
                //获取卡过期时间
                if($dom->tagName == "cardDetails")
                    foreach ($dom->childNodes as $dom_1){
                        if($dom_1->tagName == "cardExpiration")
                            $list['cardExpiration'] = $dom_1->textContent ?? '';
                        if($dom_1->tagName == "cardStatus")
                            $list['cardStatus'] = $dom_1->textContent ?? '';
                        if($dom_1->tagName == "cardFirstName")
                            $list['cardFirstName'] = $dom_1->textContent ?? '';
                        if($dom_1->tagName == "cardLastName")
                            $list['cardLastName'] = $dom_1->textContent ?? '';
                    }
                //获取卡总金额cycleAmountLimit | 获取卡余额cycleAmountLimitAvailable
                if($dom->tagName == "amountLimits")
                    foreach ($dom->childNodes as $dom_1){
                        if($dom_1->tagName == "cycleAmountLimit")
                            $list['cycleAmountLimit'] = $dom_1->textContent ?? '';
                        if($dom_1->tagName == "cycleAmountLimitAvailable")
                            $list['cycleAmountLimitAvailable'] = $dom_1->textContent ?? '';
                        if($dom_1->tagName == "cycleAmountLimitUsed")
                            $list['cycleAmountLimitUsed'] = $dom_1->textContent ?? '';
                        if($dom_1->tagName == "cycleAmountLimitHold")
                            $list['cycleAmountLimitHold'] = $dom_1->textContent ?? '';
                    }
            }
            else if($action_type == "updateCardLimits" || $action_type == "add_card_balance" || $action_type == "deduct_card_balance"){
                if($dom->tagName == "responseDescription")
                    $list['responseDescription'] = $dom->textContent ?? '';
                if($dom->tagName == "responseCode")
                    $list['responseCode'] = $dom->textContent ?? '';
            }
            else if($action_type == "searchCvv"){
                if($dom->tagName == "cardSecurityCode")
                    $list['cardSecurityCode'] = $dom->textContent ?? '';
            }
            else if($action_type == "search_account"){
                if($dom->tagName == "ArrayOfAvailableCreditInquiryRecords")
                    foreach ($dom->childNodes as $dom_1){
                        if($dom_1->tagName == "AvailableCreditInquiryRecords")
                            foreach ($dom_1->childNodes as $dom_2) {
                                if($dom_2->tagName == "accountCode")
                                    $list['accountCode'] = $dom_2->textContent ?? '';
                                if($dom_2->tagName == "accountBalance")
                                    $list['accountBalance'] = $dom_2->textContent ?? '';
                            }
                    }
            }
            else if($action_type == "search_funds"){
                if($dom->tagName == "records")
                    foreach ($dom->childNodes as $dom_1){
                        $list_1 = [];
                        if($dom_1->tagName == "PaymentHistoryRecord")
                            foreach ($dom_1->childNodes as $dom_2) {
                                if($dom_2->tagName == "paymentDate")
                                    $list_1['paymentDate'] = $dom_2->textContent ?? '';
                                if($dom_2->tagName == "paymentAmt")
                                    $list_1['paymentAmt'] = $dom_2->textContent ?? '';
                                if($dom_2->tagName == "paymentSrcCd")
                                    $list_1['paymentSrcCd'] = $dom_2->textContent ?? '';
                                if($dom_2->tagName == "paymentStatus")
                                    $list_1['paymentStatus'] = $dom_2->textContent ?? '';

                            }
                        $list[] = $list_1;
                    }
            }
            else if($action_type == "search_trans" ||
                $action_type == "search_trans_only" ||
                $action_type == "search_trans_test" ||
                $action_type == "search_trans_all"
            ) {
                if($dom->tagName == "records"){
                    foreach ($dom->childNodes as $dom_records){
                        $list_records = [];
                        if($dom_records->tagName == "RtTransactionRecord"){
                            foreach ($dom_records->childNodes as $dom_22) {
                                if($dom_22->tagName == "transactionStatus")
                                    $list_records['transactionStatus'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "cardNumber")
                                    $list_records['cardNumber'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "approvalCode")
                                    $list_records['approvalCode'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "merchantName")
                                    $list_records['merchantName'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "acceptLocation")
                                    $list_records['acceptLocation'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "transactionDate")
                                    $list_records['transactionDate'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "transactionTime")
                                    $list_records['transactionTime'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "postedDate")
                                    $list_records['postedDate'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "postedTime")
                                    $list_records['postedTime'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "preAuthAmount")
                                    $list_records['preAuthAmount'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "postedAmount")
                                    $list_records['postedAmount'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "reversalFlag")
                                    $list_records['reversalFlag'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "declineMessage")
                                    $list_records['declineMessage'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "correctiveAction")
                                    $list_records['correctiveAction'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "idMatchNumber")
                                    $list_records['idMatchNumber'] = $dom_22->textContent ?? '';
                            }
                        }
                        $list[] = $list_records;
                    }
                }
            }
            else if($action_type == "up_card_balance"){
                if($dom->tagName == "records"){
                    foreach ($dom->childNodes as $dom_records){
                        $list_records = [];
                        if($dom_records->tagName == "card"){
                            foreach ($dom_records->childNodes as $dom_22) {
                                if($dom_22->tagName == "cardToken")
                                    $list_records['cardToken'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "amountLimits"){
                                    foreach ($dom_22->childNodes as $dom_33) {
                                        if($dom_33->tagName == "cycleAmountLimitAvailable")
                                            $list_records['cycleAmountLimitAvailable'] = $dom_33->textContent ?? '';
                                    }
                                }
                            }
                        }
                        $list[] = $list_records;
                    }
                }
            }
        }

        if(empty($error_code)){
            /** **/
            foreach ($xml_read->lastChild->lastChild->lastChild->lastChild->childNodes as $dom){
                if($action_type == "addCard"){
                    if($dom->tagName == "cardNumber"){
                        $list['cardNumber'] = $dom->textContent ?? '';
                        $card_num           = $dom->textContent ?? '';
                    }
                    if($dom->tagName == "cardToken"){
                        $list['cardToken'] = $dom->textContent ?? '';
                    }
                }
                else if($action_type == "updateCard" ||
                    $action_type == "card_active" ||
                    $action_type == "card_active_new" ||
                    $action_type == "card_suspended" ||
                    $action_type == "card_del" ||
                    $action_type == "card_del_unReal"
                ){
                    if($dom->tagName == "responseDescription"){
                        $list['responseDescription'] = $dom->textContent ?? '  ';
                    }
                }
            }
            if(!empty($list)){
                $return_result = ['blog' => true,'list'  =>$list];
            }else{
                $return_result = ['blog' => false,'list' =>['error_string' => 'api_getData_error']];
            }
        }else{
            $return_result = ['blog' => false,'list' =>['error_string' => $error_string]];
        }
        if($action_type == "search_trans"
            || $action_type == "search_trans_test"
            || $action_type == "search_trans_all"
            || $action_type == "up_card_balance"
            || $action_type == "searchExpDate2"
            || $action_type == "search_funds"
        ){
        }else if($action_type == "search_trans_only"){
            $update_time_ymd  = date("Y-m-d");
            $only_list   = Db::name('cards_trans_only_num')
                ->where(['user_id'=>$user_id])->find();
            if(empty($only_list)){
                Db::name('cards_trans_only_num')->save([
                    'user_id'       => $user_id,
                    'request_num'   => 1,
                    'date'          => $update_time_ymd
                ]);
            }else{
                $num        = $only_list['request_num'] ?? 0;
                $date       = $only_list['date'] ?? $update_time_ymd;
                if($date == $update_time_ymd){
                    Db::name('cards_trans_only_num')
                        ->where(['user_id'=>$user_id])
                        ->update(['request_num' => $num + 1]);
                }else{
                    Db::name('cards_trans_only_num')
                        ->where(['user_id'=>$user_id])
                        ->update(['request_num'=> 0,'date'=>$update_time_ymd]);
                }
            }
        }else{
            Db::name('cd_api_log')->save([
                'user_id'           => $user_id,
                'name'              => $action_type,
                'card_num'          => $card_num,
                'ip'                => get_client_ip(),
                'header'            => $soap_action,
                'method'            => 'POST',
                'request'           => $soap_body,
                'response'          => $response,
                'response_json'     => json_encode($return_result),
                'ctime'             => getUtcTime()
            ]);
        }
        return $return_result;
    }

    public static function xmlSendNew($param = [])
    {
        $action_type    = $param['action_type'];
        $customerCode   = $param['customerCode'];
        $customerId     = $param['customerId'];
        $username       = 'WSPPTCO';
        $password       = '9YJRsbjz3JC4';
        $soap_header=  '<soapenv:Header>
                            <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                                <wsse:UsernameToken>
                                    <wsse:Username>' . $username . '</wsse:Username>
                                    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $password . '</wsse:Password>
                                </wsse:UsernameToken>
                            </wsse:Security>
                        </soapenv:Header>';
        $soap_body  = '';
        $soap_action= '';

        $user_id        = $param['user_id'] ?? 1;
        $card_num       = $param['card_num'] ?? '';
        switch ($action_type){
            case "searchCard2Token":
                $card_token     = $param['card_token'];
                $soap_action    = "inquireCardV02";
                $soap_body      =  "<main:CardInquiryRequestV02>
                                    <accountCode>{$customerCode}</accountCode>
                                    <customerId>{$customerId}</customerId>
                                    <cardIdentifierType>T</cardIdentifierType>
                                    <cardIdentifier>{$card_token}</cardIdentifier>
                                    </main:CardInquiryRequestV02>";
                break;
            case "card_suspended":
                $soap_action    = "updateCardV02";
                //1
                $soap_body      = self::updateCardStatus($customerCode,$customerId,$card_num,'B');
                break;
            default:
                break;
        }
        $xml_post_string = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:main="http://fleetCredit02.comdata.com/maintenance/">';
        $xml_post_string.=  $soap_header;
        $xml_post_string.=  '<soapenv:Body>';
        $xml_post_string.=  $soap_body;
        $xml_post_string.=  '</soapenv:Body>';
        $xml_post_string.=  '</soapenv:Envelope>';

        $url        = "https://api.iconnectdata.com/FleetCreditWS/services/FleetCreditWS0200/wsdl/FleetCreditWS0200.wsdl";
        $header     = [
            'trace' => TRUE,
            'exceptions' => TRUE,
            'cache_wsdl' => WSDL_CACHE_BOTH,
            'stream_context' => stream_context_create(array(
                'http' => array(
                    'header' => 'SOAPAction: "http://fleetCredit02.comdata.com/FleetCreditWS0200/' . $soap_action . '"'
                ),
            ))
        ];
        $soapClient = new \SoapClient($url, $header);
        $response = $soapClient->__doRequest($xml_post_string, 'https://api.iconnectdata.com/FleetCreditWS/services/FleetCreditWS0200', $soap_action, SOAP_1_2);

        $xml_read = new \DOMDocument();
        //有可能api请求频繁,导致获取到空值
        if(empty($response)){
            $return_result = ['blog' => false,'list' =>['error_string' => 'get data error']];
            Db::name('cd_api_log')->save([
                'user_id'           => $user_id,
                'name'              => $action_type,
                'card_num'          => $card_num,
                'ip'                => get_client_ip(),
                'header'            => $soap_action,
                'method'            => 'POST',
                'request'           => $soap_body,
                'response'          => $response,
                'response_json'     => json_encode($return_result),
                'ctime'             => getUtcTime()
            ]);
            return $return_result;
        }
        $xml_read->loadXML($response);

        /** 先判断错误 **/
        $error_code     = '';
        $error_string   = '';
        $list           = [];
        foreach ($xml_read->lastChild->lastChild->lastChild->childNodes as $dom){
            if($dom->tagName == "faultcode"){
                $error_code     = $dom->textContent ?? '';
            }
            if($dom->tagName == "faultstring"){
                $error_string   = $dom->textContent ?? '';
            }
            if($action_type == "searchExpDate" || $action_type == "searchCard2Token" || $action_type == "searchExpDate2"){
                //获取卡号
                if($dom->tagName == "cardNumber")
                    $list['cardNumber'] = $dom->textContent ?? '';
                //获取卡过期时间
                if($dom->tagName == "cardDetails")
                    foreach ($dom->childNodes as $dom_1){
                        if($dom_1->tagName == "cardExpiration")
                            $list['cardExpiration'] = $dom_1->textContent ?? '';
                        if($dom_1->tagName == "cardStatus")
                            $list['cardStatus'] = $dom_1->textContent ?? '';
                        if($dom_1->tagName == "cardFirstName")
                            $list['cardFirstName'] = $dom_1->textContent ?? '';
                        if($dom_1->tagName == "cardLastName")
                            $list['cardLastName'] = $dom_1->textContent ?? '';
                    }
                //获取卡总金额cycleAmountLimit | 获取卡余额cycleAmountLimitAvailable
                if($dom->tagName == "amountLimits")
                    foreach ($dom->childNodes as $dom_1){
                        if($dom_1->tagName == "cycleAmountLimit")
                            $list['cycleAmountLimit'] = $dom_1->textContent ?? '';
                        if($dom_1->tagName == "cycleAmountLimitAvailable")
                            $list['cycleAmountLimitAvailable'] = $dom_1->textContent ?? '';
                        if($dom_1->tagName == "cycleAmountLimitUsed")
                            $list['cycleAmountLimitUsed'] = $dom_1->textContent ?? '';
                        if($dom_1->tagName == "cycleAmountLimitHold")
                            $list['cycleAmountLimitHold'] = $dom_1->textContent ?? '';
                    }
            }
            else if($action_type == "updateCardLimits" || $action_type == "add_card_balance" || $action_type == "deduct_card_balance"){
                if($dom->tagName == "responseDescription")
                    $list['responseDescription'] = $dom->textContent ?? '';
                if($dom->tagName == "responseCode")
                    $list['responseCode'] = $dom->textContent ?? '';
            }
            else if($action_type == "searchCvv"){
                if($dom->tagName == "cardSecurityCode")
                    $list['cardSecurityCode'] = $dom->textContent ?? '';
            }
            else if($action_type == "search_account"){
                if($dom->tagName == "ArrayOfAvailableCreditInquiryRecords")
                    foreach ($dom->childNodes as $dom_1){
                        if($dom_1->tagName == "AvailableCreditInquiryRecords")
                            foreach ($dom_1->childNodes as $dom_2) {
                                if($dom_2->tagName == "accountCode")
                                    $list['accountCode'] = $dom_2->textContent ?? '';
                                if($dom_2->tagName == "accountBalance")
                                    $list['accountBalance'] = $dom_2->textContent ?? '';
                            }
                    }
            }
            else if($action_type == "search_funds"){
                if($dom->tagName == "records")
                    foreach ($dom->childNodes as $dom_1){
                        $list_1 = [];
                        if($dom_1->tagName == "PaymentHistoryRecord")
                            foreach ($dom_1->childNodes as $dom_2) {
                                if($dom_2->tagName == "paymentDate")
                                    $list_1['paymentDate'] = $dom_2->textContent ?? '';
                                if($dom_2->tagName == "paymentAmt")
                                    $list_1['paymentAmt'] = $dom_2->textContent ?? '';
                                if($dom_2->tagName == "paymentSrcCd")
                                    $list_1['paymentSrcCd'] = $dom_2->textContent ?? '';
                                if($dom_2->tagName == "paymentStatus")
                                    $list_1['paymentStatus'] = $dom_2->textContent ?? '';

                            }
                        $list[] = $list_1;
                    }
            }
            else if($action_type == "search_trans" ||
                $action_type == "search_trans_only" ||
                $action_type == "search_trans_test" ||
                $action_type == "search_trans_all"
            ) {
                if($dom->tagName == "records"){
                    foreach ($dom->childNodes as $dom_records){
                        $list_records = [];
                        if($dom_records->tagName == "RtTransactionRecord"){
                            foreach ($dom_records->childNodes as $dom_22) {
                                if($dom_22->tagName == "transactionStatus")
                                    $list_records['transactionStatus'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "cardNumber")
                                    $list_records['cardNumber'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "approvalCode")
                                    $list_records['approvalCode'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "merchantName")
                                    $list_records['merchantName'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "acceptLocation")
                                    $list_records['acceptLocation'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "transactionDate")
                                    $list_records['transactionDate'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "transactionTime")
                                    $list_records['transactionTime'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "postedDate")
                                    $list_records['postedDate'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "postedTime")
                                    $list_records['postedTime'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "preAuthAmount")
                                    $list_records['preAuthAmount'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "postedAmount")
                                    $list_records['postedAmount'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "reversalFlag")
                                    $list_records['reversalFlag'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "declineMessage")
                                    $list_records['declineMessage'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "correctiveAction")
                                    $list_records['correctiveAction'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "idMatchNumber")
                                    $list_records['idMatchNumber'] = $dom_22->textContent ?? '';
                            }
                        }
                        $list[] = $list_records;
                    }
                }
            }
            else if($action_type == "up_card_balance"){
                if($dom->tagName == "records"){
                    foreach ($dom->childNodes as $dom_records){
                        $list_records = [];
                        if($dom_records->tagName == "card"){
                            foreach ($dom_records->childNodes as $dom_22) {
                                if($dom_22->tagName == "cardToken")
                                    $list_records['cardToken'] = $dom_22->textContent ?? '';
                                if($dom_22->tagName == "amountLimits"){
                                    foreach ($dom_22->childNodes as $dom_33) {
                                        if($dom_33->tagName == "cycleAmountLimitAvailable")
                                            $list_records['cycleAmountLimitAvailable'] = $dom_33->textContent ?? '';
                                    }
                                }
                            }
                        }
                        $list[] = $list_records;
                    }
                }
            }
        }

        if(empty($error_code)){
            /** **/
            foreach ($xml_read->lastChild->lastChild->lastChild->lastChild->childNodes as $dom){
                if($action_type == "addCard"){
                    if($dom->tagName == "cardNumber"){
                        $list['cardNumber'] = $dom->textContent ?? '';
                        $card_num           = $dom->textContent ?? '';
                    }
                    if($dom->tagName == "cardToken"){
                        $list['cardToken'] = $dom->textContent ?? '';
                    }
                }
                else if($action_type == "updateCard" ||
                    $action_type == "card_active" ||
                    $action_type == "card_active_new" ||
                    $action_type == "card_suspended" ||
                    $action_type == "card_del" ||
                    $action_type == "card_del_unReal"
                ){
                    if($dom->tagName == "responseDescription"){
                        $list['responseDescription'] = $dom->textContent ?? '  ';
                    }
                }
            }
            if(!empty($list)){
                $return_result = ['blog' => true,'list'  =>$list];
            }else{
                $return_result = ['blog' => false,'list' =>['error_string' => 'api_getData_error']];
            }
        }else{
            $return_result = ['blog' => false,'list' =>['error_string' => $error_string]];
        }
        if($action_type == "search_trans"
            || $action_type == "search_trans_test"
            || $action_type == "search_trans_all"
            || $action_type == "up_card_balance"
            || $action_type == "searchExpDate2"
            || $action_type == "search_funds"
        ){
        }else if($action_type == "search_trans_only"){
            $update_time_ymd  = date("Y-m-d");
            $only_list   = Db::name('cards_trans_only_num')
                ->where(['user_id'=>$user_id])->find();
            if(empty($only_list)){
                Db::name('cards_trans_only_num')->save([
                    'user_id'       => $user_id,
                    'request_num'   => 1,
                    'date'          => $update_time_ymd
                ]);
            }else{
                $num        = $only_list['request_num'] ?? 0;
                $date       = $only_list['date'] ?? $update_time_ymd;
                if($date == $update_time_ymd){
                    Db::name('cards_trans_only_num')
                        ->where(['user_id'=>$user_id])
                        ->update(['request_num' => $num + 1]);
                }else{
                    Db::name('cards_trans_only_num')
                        ->where(['user_id'=>$user_id])
                        ->update(['request_num'=> 0,'date'=>$update_time_ymd]);
                }
            }
        }else{
            Db::name('cd_api_log')->save([
                'user_id'           => $user_id,
                'name'              => $action_type,
                'card_num'          => $card_num,
                'ip'                => get_client_ip(),
                'header'            => $soap_action,
                'method'            => 'POST',
                'request'           => $soap_body,
                'response'          => $response,
                'response_json'     => json_encode($return_result),
                'ctime'             => getUtcTime()
            ]);
        }
        return $return_result;
    }
    /**
     * 更新卡余额限制
     * @param $accountCode
     * @param $customerId
     * @param $card_num
     * @param $card_balance
     * @return string
     */
    public static function cardProfileXml($accountCode,$customerId,$card_num,$card_balance)
    {
        return "<main:CardProfileLimitUpdateRequest>
                    <requestUtil>
                        <accountCode>{$accountCode}</accountCode>
                        <customerId>{$customerId}</customerId>
                        <productCode>10000</productCode>
                    </requestUtil>
                    <empNumCardNumFlag>C</empNumCardNumFlag>
                    <empNumCardNumValue>{$card_num}</empNumCardNumValue>
                    <profileLimits>
                        <openCloseFlag>O</openCloseFlag>
                        <productAvailableFlag>Y</productAvailableFlag>
                        <transactionDollarLimit>{$card_balance}</transactionDollarLimit>
                        <dailyDollarLimit>{$card_balance}</dailyDollarLimit>
                        <dailyTransactionLimit>999</dailyTransactionLimit>
                        <cycleDollarLimit>{$card_balance}</cycleDollarLimit>
                        <cycleTransactionLimit>999</cycleTransactionLimit>
                        <cycleType>T</cycleType>
                        <cycleDay>T</cycleDay>
                    </profileLimits>
                </main:CardProfileLimitUpdateRequest>";
    }

    public static function updateCardStatus($accountCode,$customerId,$card_num,$cardStatus)
    {
        return "<main:UpdateCardRequestV02>
                     <cardIdentifierType>C</cardIdentifierType>
                     <cardIdentifier>{$card_num}</cardIdentifier>
                     <cardDetails>
                          <accountCode>{$accountCode}</accountCode>
                          <customerId>{$customerId}</customerId>
                          <cardStatus>{$cardStatus}</cardStatus>
                     </cardDetails>
                </main:UpdateCardRequestV02>";
    }

    public static function updateCardStatusNew($accountCode,$customerId,$card_num,$cardStatus)
    {
        return "<main:UpdateCardRequestV02>
                     <cardIdentifierType>C</cardIdentifierType>
                     <cardIdentifier>{$card_num}</cardIdentifier>
                     <cardDetails>
                          <accountCode>{$accountCode}</accountCode>
                          <customerId>{$customerId}</customerId>
                          <cardStatus>{$cardStatus}</cardStatus>
                          <cardFirstName>huang</cardFirstName>
                          <cardLastName>zhen</cardLastName>
                     </cardDetails>
                </main:UpdateCardRequestV02>";
    }
}
